package com.gang.lingdian.readwrite;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author gaoyonggang
 * @date 2021/11/4 19:21
 * desc 演示读写锁
 */

// 创建资源类
class myCache{

    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    private volatile Map<String, Object> map = new HashMap<>();

    public void write(String key,Object value){
        readWriteLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"正在写操作"+key);
            TimeUnit.MICROSECONDS.sleep(300);
            map.put(key, value);
            System.out.println(Thread.currentThread().getName()+"写操作完成"+key);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            readWriteLock.writeLock().unlock();
        }
    }

    public Object read(String key){
        readWriteLock.readLock().lock();
        Object result = null;
        try {
            System.out.println(Thread.currentThread().getName()+"正在读取操作"+key);
            TimeUnit.MICROSECONDS.sleep(300);
            result = map.get(key);
            System.out.println(Thread.currentThread().getName()+"读取完成"+key);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            readWriteLock.readLock().unlock();
        }
        return result;
    }

}


public class ReadWriteLockDemo {

    public static void main(String[] args) {
        myCache myCache = new myCache();

        // 创建5个线程进行写操作
        for (int i = 1; i <= 5; i++) {
            final int num = i;
            new Thread(()->{
                myCache.write(num+"",num);
            },String.valueOf(i)).start();
        }

        for (int i = 1; i <= 5; i++) {
            final int num = i;
            new Thread(()->{
                myCache.read(num+"");
            },String.valueOf(i)).start();
        }
    }
}
